package com.ruoyi.common.utils.encode;

import java.math.BigInteger;

/**
 * Base62 编码工具类
 */
public class Base62 {

    private static final char[] BASE62_CHARS =
        "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();

    /**
     * 将字节数组编码为Base62字符串
     * @param data 要编码的字节数组
     * @return Base62编码字符串
     */
    public static String encode(byte[] data) {
        if (data == null || data.length == 0) {
            return "";
        }

        // 1. 将字节数组转换为大整数（无符号）
        BigInteger bigInt = new BigInteger(1, data);
        StringBuilder sb = new StringBuilder();

        // 2. 进行Base62转换
        while (bigInt.compareTo(BigInteger.ZERO) > 0) {
            BigInteger[] divRem = bigInt.divideAndRemainder(BigInteger.valueOf(62));
            sb.insert(0, BASE62_CHARS[divRem[1].intValue()]);
            bigInt = divRem[0];
        }

        // 3. 处理前导零
        for (byte b : data) {
            if (b == 0) {
                sb.insert(0, BASE62_CHARS[0]);
            } else {
                break;
            }
        }

        return sb.toString();
    }
}

